import React, {useEffect, useState} from 'react';
import {Button, Card, Col, Input, message, Row, Spin, Statistic, Typography} from "antd";
import {
    ArrowRightOutlined,
    ClockCircleOutlined,
    CloudOutlined,
    CloudServerOutlined,
    DatabaseOutlined,
    ReloadOutlined
} from '@ant-design/icons';
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";

const {Title, Text, Paragraph} = Typography;

const ConsoleIndexPage = () => {
    // 消息提示
    const [messageApi, contextHolder] = message.useMessage();

    // 后端路由状态
    const [backRouteType, setBackRouteType] = React.useState('');
    const [backRouteAddress, setBackRouteAddress] = React.useState('');

    // 统计数据状态
    const [serviceGovernanceCountResp, setServiceGovernanceCountResp] = React.useState([]);
    const [operationLogCountResp, setOperationLogCountResp] = React.useState({});
    const [loading, setLoading] = useState(true);

    // 交互状态（用于动态效果）
    const [hoverStates, setHoverStates] = useState({});
    const [activeCard, setActiveCard] = useState(null);

    // 更新路由类型
    const updateBackRoute = () => {
        setBackRouteType(RequestUtils.getCurrentBackRouteType());
        setBackRouteAddress(RequestUtils.getCurrentGatewayAddress());
    };

    // 切换网关路由
    const editBackRoute = (type) => {
        setLoading(true);
        localStorage.setItem("BACK_ROUTE", type);
        updateBackRoute();
        setTimeout(() => {
            searchServiceGovernanceCount();
            searchOperationLogCount();
        }, 500);
    }

    // 查询服务数据
    const searchServiceGovernanceCount = () => {
        setLoading(true);
        RequestUtils.post(RequestApis.dashboard.searchServiceGovernanceCount, {})
            .then((res) => {
                setServiceGovernanceCountResp(res.data.data);
                setLoading(false);
            }).catch(err => {
            messageApi.error(err.message);
            setLoading(false);
        });
    }

    // 查询接口统计
    const searchOperationLogCount = () => {
        setLoading(true);
        RequestUtils.post(RequestApis.dashboard.searchOperationLogCount, {})
            .then(res => {
                setOperationLogCountResp(res.data.data);
                setLoading(false);
            }).catch(err => {
            messageApi.error(err.message);
            setLoading(false);
        });
    }

    // 刷新数据
    const refreshAllData = () => {
        setLoading(true);
        // 添加刷新按钮旋转动画
        setHoverStates(prev => ({...prev, refreshSpin: true}));
        searchServiceGovernanceCount();
        searchOperationLogCount();
        messageApi.success('数据刷新中...');

        // 1秒后停止旋转动画
        setTimeout(() => {
            setHoverStates(prev => ({...prev, refreshSpin: false}));
        }, 1000);
    }

    // 处理卡片交互动画
    const handleCardInteraction = (key, isHover) => {
        setHoverStates(prev => ({...prev, [key]: isHover}));
        if (isHover) {
            setActiveCard(key);
        } else if (activeCard === key) {
            setActiveCard(null);
        }
    }

    // 初始化加载
    useEffect(() => {
        updateBackRoute();
        searchServiceGovernanceCount();
        searchOperationLogCount();
        // eslint-disable-next-line
    }, []);

    // 卡片样式配置 - 增强边框可见性
    const cardStyles = {
        base: {
            borderRadius: '12px',
            border: '1px solid #e0e0e0',
            transition: 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)',
            overflow: 'hidden'
        },
        hover: {
            boxShadow: '0 8px 24px rgba(0, 0, 0, 0.08)',
            borderColor: '#d0d0d0'
        },
        gateway: {
            background: 'linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%)',
            borderColor: '#bfdbfe'
        },
        service: {
            background: 'linear-gradient(135deg, #F7F2FF 0%, #FBF7FF 100%)',
            borderColor: '#e9d5ff'
        },
        stats: {
            background: 'linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%)',
            borderColor: '#bbf7d0'
        },
        topApi: {
            background: 'rgba(255, 255, 255, 0.7)',
            borderColor: '#e5e7eb'
        }
    };

    return (
        <div style={{
            paddingTop: '16px',
            margin: '0 auto',
            minHeight: '100vh',
            transition: 'all 0.5s ease',
            maxWidth: '1400px',
            padding: '0 20px'
        }}>
            {contextHolder}

            {/* 页面标题区域 */}
            <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '24px',
                paddingBottom: '16px',
                borderBottom: '1px solid #e2e8f0',
                position: 'relative',
                overflow: 'hidden'
            }}>
                {/* 标题装饰元素 */}
                <div style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: '80px',
                    height: '80px',
                    background: 'rgba(24, 144, 255, 0.05)',
                    borderRadius: '50%',
                    transform: 'translate(-50%, -50%)',
                    zIndex: 0
                }}></div>

                <Title level={2} style={{
                    margin: 0,
                    color: '#1e293b',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '12px',
                    position: 'relative',
                    zIndex: 1
                }}>
                    <CloudServerOutlined style={{
                        color: '#3b82f6',
                        fontSize: '28px',
                        transition: 'transform 0.3s ease',
                        transform: hoverStates.titleIcon ? 'rotate(5deg)' : 'rotate(0)'
                    }}
                                         onMouseEnter={() => setHoverStates(prev => ({...prev, titleIcon: true}))}
                                         onMouseLeave={() => setHoverStates(prev => ({...prev, titleIcon: false}))}
                    />
                    仪表板
                </Title>

                <Button
                    color='purple'
                    variant='solid'
                    onClick={refreshAllData}
                    style={{marginRight: '24px', width: '260px'}}
                >
                    <ReloadOutlined style={{marginRight: '10px'}} />
                    刷新仪表板数据
                </Button>
            </div>

            {/* 网关路由配置卡片 - 淡蓝色渐变 */}
            <Card
                style={{
                    ...cardStyles.base,
                    ...cardStyles.gateway,
                    marginBottom: '32px',
                    ...(hoverStates.routeCard ? cardStyles.hover : {
                        boxShadow: '0 4px 20px rgba(59, 130, 246, 0.08)'
                    })
                }}
                onMouseEnter={() => handleCardInteraction('routeCard', true)}
                onMouseLeave={() => handleCardInteraction('routeCard', false)}
            >
                <div style={{marginBottom: '24px'}}>
                    <Title level={4} style={{
                        margin: '0 0 8px 0',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px',
                        color: '#1e293b',
                        fontWeight: '600'
                    }}>
                        <CloudOutlined style={{color: '#3b82f6'}}/> 网关路由配置
                    </Title>
                    <Text type="secondary">当前路由模式将影响所有接口请求的目标地址</Text>
                </div>

                <div style={{
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '20px'
                }}>
                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '12px',
                        flexWrap: 'wrap'
                    }}>
                        <span style={{
                            whiteSpace: 'nowrap',
                            color: '#475569',
                            fontWeight: '500',
                            fontSize: '14px'
                        }}>当前网关地址：</span>
                        <Input
                            style={{
                                flex: 1,
                                minWidth: '200px',
                                borderRadius: '8px',
                                border: '1px solid #bfdbfe',
                                background: 'rgba(255, 255, 255, 0.7)',
                                boxShadow: 'inset 0 1px 2px rgba(0, 0, 0, 0.05)',
                                transition: 'all 0.3s ease'
                            }}
                            value={backRouteAddress}
                            disabled={true}
                            placeholder="网关地址"
                        />
                    </div>

                    <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '16px',
                        flexWrap: 'wrap'
                    }}>
                        {backRouteType === 'localhost' ? (
                            <>
                                <Text style={{
                                    fontSize: '14px',
                                    fontWeight: '500',
                                    padding: '6px 16px',
                                    borderRadius: '20px',
                                    backgroundColor: 'rgba(16, 185, 129, 0.1)',
                                    color: '#059669',
                                    boxShadow: '0 2px 4px rgba(16, 185, 129, 0.1)'
                                }}>当前：本地网关</Text>
                                <Button
                                    type="primary"
                                    style={{
                                        borderRadius: '8px',
                                        padding: '8px 20px',
                                        fontWeight: '500',
                                        display: 'flex',
                                        alignItems: 'center',
                                        gap: '8px',
                                        transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                                        border: 'none',
                                        background: 'linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%)',
                                        boxShadow: '0 4px 12px rgba(59, 130, 246, 0.15)',
                                        ...(hoverStates.switchToServer ? {
                                            transform: 'translateY(-2px)',
                                            boxShadow: '0 6px 16px rgba(59, 130, 246, 0.25)'
                                        } : {})
                                    }}
                                    onMouseEnter={() => handleCardInteraction('switchToServer', true)}
                                    onMouseLeave={() => handleCardInteraction('switchToServer', false)}
                                    onClick={() => editBackRoute('server')}
                                >
                                    切换至线上网关 <ArrowRightOutlined style={{
                                    transition: 'transform 0.3s ease',
                                    transform: hoverStates.switchToServer ? 'translateX(2px)' : 'translateX(0)'
                                }}/>
                                </Button>
                            </>
                        ) : (
                            <>
                                <Text style={{
                                    fontSize: '14px',
                                    fontWeight: '500',
                                    padding: '6px 16px',
                                    borderRadius: '20px',
                                    backgroundColor: 'rgba(245, 158, 11, 0.1)',
                                    color: '#d97706',
                                    boxShadow: '0 2px 4px rgba(245, 158, 11, 0.1)'
                                }}>当前：线上网关</Text>
                                <Button
                                    type="primary"
                                    style={{
                                        borderRadius: '8px',
                                        padding: '8px 20px',
                                        fontWeight: '500',
                                        display: 'flex',
                                        alignItems: 'center',
                                        gap: '8px',
                                        transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                                        border: 'none',
                                        background: 'linear-gradient(135deg, #10b981 0%, #34d399 100%)',
                                        boxShadow: '0 4px 12px rgba(16, 185, 129, 0.15)',
                                        ...(hoverStates.switchToLocal ? {
                                            transform: 'translateY(-2px)',
                                            boxShadow: '0 6px 16px rgba(16, 185, 129, 0.25)'
                                        } : {})
                                    }}
                                    onMouseEnter={() => handleCardInteraction('switchToLocal', true)}
                                    onMouseLeave={() => handleCardInteraction('switchToLocal', false)}
                                    onClick={() => editBackRoute('localhost')}
                                >
                                    切换至本地网关 <ArrowRightOutlined style={{
                                    transition: 'transform 0.3s ease',
                                    transform: hoverStates.switchToLocal ? 'translateX(2px)' : 'translateX(0)'
                                }}/>
                                </Button>
                            </>
                        )}
                    </div>
                </div>
            </Card>

            {/* 服务实例统计区域 */}
            <div style={{
                margin: '0 0 16px 0',
                paddingTop: '16px',
                position: 'relative'
            }}>
                <Title level={4} style={{
                    margin: 0,
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    color: '#1e293b',
                    fontWeight: '600'
                }}>
                    <DatabaseOutlined style={{color: '#8b5cf6'}}/> 服务实例状态
                </Title>
                <div style={{
                    height: '2px',
                    width: '40px',
                    background: 'linear-gradient(90deg, #8b5cf6 0%, #a78bfa 100%)',
                    marginTop: '8px',
                    borderRadius: '1px'
                }}></div>
            </div>

            <Spin
                spinning={loading}
                tip="加载服务数据中..."
                style={{minHeight: '200px'}}
                indicator={<Spin size="large" style={{color: '#8b5cf6'}}/>}
            >
                <Row gutter={[24, 24]}>
                    {serviceGovernanceCountResp && serviceGovernanceCountResp.length > 0 ? (
                        serviceGovernanceCountResp.map((item, index) => (
                            <Col
                                xs={24}
                                sm={12}
                                md={8}
                                key={index}
                                style={{display: 'flex', marginBottom: '16px'}}
                            >
                                {/* 服务实例卡片 - 淡紫色渐变 */}
                                <Card
                                    style={{
                                        ...cardStyles.base,
                                        ...cardStyles.service,
                                        flex: 1,
                                        ...(hoverStates[`service${index}`] ? cardStyles.hover : {
                                            boxShadow: '0 4px 20px #F2E9FF'
                                        })
                                    }}
                                    onMouseEnter={() => handleCardInteraction(`service${index}`, true)}
                                    onMouseLeave={() => handleCardInteraction(`service${index}`, false)}
                                >
                                    <div style={{
                                        display: 'flex',
                                        justifyContent: 'space-between',
                                        alignItems: 'flex-start',
                                        marginBottom: '16px',
                                        paddingBottom: '12px',
                                        borderBottom: '1px solid #f0e6fd'
                                    }}>
                                        <Title level={5} style={{
                                            margin: 0,
                                            color: '#1e293b',
                                            fontWeight: '600'
                                        }}>{item.serviceTitle}</Title>
                                        <Statistic
                                            title="在线实例"
                                            value={item.healthyInstanceCount ?? 0}
                                            valueStyle={{
                                                color: item.healthyInstanceCount > 0 ? '#10b981' : '#ef4444',
                                                fontSize: '24px',
                                                fontWeight: '600'
                                            }}
                                        />
                                    </div>
                                    <div style={{
                                        flex: 1,
                                        display: 'flex',
                                        flexDirection: 'column',
                                        justifyContent: 'center'
                                    }}>
                                        <Paragraph>
                                            <Text strong style={{color: '#475569'}}>服务名称：</Text>
                                            <Text style={{color: '#334155'}}>{item.serviceName}</Text>
                                        </Paragraph>
                                    </div>
                                </Card>
                            </Col>
                        ))
                    ) : (
                        <Col span={24} style={{
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            padding: '60px 0',
                            color: '#64748b',
                            backgroundColor: '#fff',
                            borderRadius: '12px',
                            boxShadow: '0 4px 20px rgba(0, 0, 0, 0.05)',
                            border: '1px solid #e0e0e0',
                            transition: 'all 0.3s ease'
                        }}>
                            <Text type="warning">暂无服务实例数据</Text>
                        </Col>
                    )}
                </Row>
            </Spin>

            {/* 接口调用统计区域 */}
            <div style={{
                margin: '0 0 16px 0',
                paddingTop: '32px',
                position: 'relative'
            }}>
                <Title level={4} style={{
                    margin: 0,
                    display: 'flex',
                    alignItems: 'center',
                    gap: '8px',
                    color: '#1e293b',
                    fontWeight: '600'
                }}>
                    <ClockCircleOutlined style={{color: '#10b981'}}/> 接口调用统计
                </Title>
                <div style={{
                    height: '2px',
                    width: '40px',
                    background: 'linear-gradient(90deg, #10b981 0%, #34d399 100%)',
                    marginTop: '8px',
                    borderRadius: '1px'
                }}></div>
            </div>

            <Spin
                spinning={loading}
                tip="加载接口统计数据中..."
                style={{minHeight: '200px'}}
                indicator={<Spin size="large" style={{color: '#10b981'}}/>}
            >
                {/* 接口统计卡片 - 淡绿色渐变 */}
                <Card
                    style={{
                        ...cardStyles.base,
                        ...cardStyles.stats,
                        marginBottom: '24px',
                        ...(hoverStates.statsCard ? cardStyles.hover : {
                            boxShadow: '0 4px 20px rgba(16, 185, 129, 0.08)'
                        })
                    }}
                    onMouseEnter={() => handleCardInteraction('statsCard', true)}
                    onMouseLeave={() => handleCardInteraction('statsCard', false)}
                >
                    <div style={{
                        padding: '12px 0 20px 0',
                        marginBottom: '16px',
                        borderBottom: '1px solid #dcfce7'
                    }}>
                        <Statistic
                            title={
                                <span style={{color: '#ff007f', fontWeight: '600', fontSize: '15px'}}>
                                今日接口调用频次
                                </span>
                            }
                            value={operationLogCountResp.todayOperationLogCount ?? 0}
                            valueStyle={{fontSize: '28px', color: '#ff0000', fontWeight: '600'}}
                        />
                    </div>

                    <div style={{paddingTop: '16px'}}>
                        <Title level={5} style={{
                            margin: '0 0 16px 0',
                            color: '#ff007f',
                            fontWeight: '600'
                        }}>高频接口调用 Top 3</Title>

                        {operationLogCountResp.highFrequencyOperationLogs &&
                        operationLogCountResp.highFrequencyOperationLogs.length > 0 ? (
                            <Row gutter={[16, 16]} style={{width: '100%'}}>
                                {operationLogCountResp.highFrequencyOperationLogs.map((item, index) => (
                                    <Col
                                        xs={24}
                                        sm={24}
                                        md={8}
                                        key={index}
                                        style={{display: 'flex', marginBottom: '16px'}}
                                    >
                                        <Card
                                            style={{
                                                ...cardStyles.base,
                                                ...cardStyles.topApi,
                                                flex: 1,
                                                position: 'relative',
                                                overflow: 'visible',
                                                borderLeft: `4px solid ${
                                                    index === 0 ? '#ef4444' :
                                                        index === 1 ? '#f59e0b' : '#6366f1'
                                                }`,
                                                ...(hoverStates[`op${index}`] ? cardStyles.hover : {
                                                    boxShadow: '0 4px 16px rgba(16, 185, 129, 0.08)'
                                                })
                                            }}
                                            onMouseEnter={() => handleCardInteraction(`op${index}`, true)}
                                            onMouseLeave={() => handleCardInteraction(`op${index}`, false)}
                                        >
                                            <div style={{
                                                position: 'absolute',
                                                top: '-10px',
                                                right: '16px'
                                            }}>
                                                <span style={{
                                                    display: 'inline-flex',
                                                    alignItems: 'center',
                                                    justifyContent: 'center',
                                                    width: '24px',
                                                    height: '24px',
                                                    borderRadius: '50%',
                                                    color: 'white',
                                                    fontSize: '14px',
                                                    fontWeight: 'bold',
                                                    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
                                                    background: index === 0 ?
                                                        'linear-gradient(135deg, #ef4444 0%, #f87171 100%)' :
                                                        index === 1 ?
                                                            'linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%)' :
                                                            'linear-gradient(135deg, #6366f1 0%, #818cf8 100%)'
                                                }}>
                                                    {index + 1}
                                                </span>
                                            </div>
                                            <div style={{
                                                position: 'relative',
                                                paddingTop: '8px',
                                                paddingRight: '10px' // 增加右侧内边距，防止内容贴边
                                            }}>
                                                <Paragraph style={{marginBottom: '16px', color: '#475569'}}>
                                                    <Text strong style={{color: '#3399ff'}}>描述：</Text>
                                                    <span style={{color: '#3399ff'}}>
                                                        {item.operationDescription || '无描述'}
                                                    </span>
                                                </Paragraph>
                                                <Paragraph style={{
                                                    marginBottom: '8px',
                                                    color: '#334155',
                                                    wordBreak: 'break-all', // 允许在单词内换行
                                                    whiteSpace: 'normal',    // 正常换行
                                                    lineHeight: 1.6          // 增加行高，提升可读性
                                                }}>
                                                    <Text strong style={{color: '#009999'}}>接口地址：</Text>
                                                    <span style={{color: '#009999'}}>
                                                        {item.uri}
                                                    </span>
                                                </Paragraph>
                                                <Statistic
                                                    title={<span style={{color: '#6600cc'}}>调用次数</span>}
                                                    value={item.invokeCount ?? 0}
                                                    valueStyle={{
                                                        color: index === 0 ? '#ef4444' :
                                                            index === 1 ? '#f59e0b' : '#6366f1',
                                                        fontWeight: '600'
                                                    }}
                                                />
                                            </div>
                                        </Card>
                                    </Col>
                                ))}
                            </Row>
                        ) : (
                            <div style={{
                                display: 'flex',
                                justifyContent: 'center',
                                alignItems: 'center',
                                padding: '60px 0',
                                color: '#64748b',
                                backgroundColor: 'rgba(255, 255, 255, 0.7)',
                                borderRadius: '12px',
                                boxShadow: '0 2px 10px rgba(0, 0, 0, 0.03)',
                                border: '1px solid #e0e0e0',
                                transition: 'all 0.3s ease'
                            }}>
                                <Text type="warning">暂无接口调用数据</Text>
                            </div>
                        )}
                    </div>
                </Card>
            </Spin>
        </div>
    );
};

export default ConsoleIndexPage;